package com.deloitte.service;

import java.util.Timer;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

/**
 * Servlet implementation class DocumentsCasheLoader
 */
public class DocumentsCasheLoader extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Timer timer = null;
	private DocumentsLoadScheduler task = null;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public DocumentsCasheLoader() {
		super();
	}

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		String loadTimeStr = config
				.getInitParameter("doc.load.schedule.seconds");
		int loadTimeInSec = new Integer(loadTimeStr);
		// start docs load scheduler
		if (loadTimeInSec > 0) {
			long period = loadTimeInSec * 1000;
			timer = new Timer();
			task = new DocumentsLoadScheduler();
			timer.scheduleAtFixedRate(task, 0, period);
		}
	}

	@Override
	public void destroy() {
		killTimers();
		System.out.println(" Destroyed " + getClass());
		super.destroy();
	}

	@Override
	protected void finalize() throws Throwable {
		killTimers();
		System.out.println(" Finalize " + getClass());
		super.finalize();
	}

	private void killTimers() {
		try {
			if (task != null) {
				task.cancel();
			}
			if (timer != null) {
				timer.cancel();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
